package com.sharding.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wl
 * @Description: 数据源配置
 * @date 2018/12/1416:41
 */
@Configuration
public class DataSourceConfig {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Bean(name="ds1")
    @ConfigurationProperties(prefix = "r.data") // application.properteis中对应属性的前缀
    public DataSource dataSource1() {
        logger.info("ds1:datasource:"+DataSourceBuilder.create().build().toString());
        //使用druid数据源需要指定druid的数据源type
        return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
    }

    @Bean(name="ds2")
    @ConfigurationProperties(prefix = "w.data") // application.properteis中对应属性的前缀
    public DataSource dataSource2() {
        logger.info("ds2:datasource:"+DataSourceBuilder.create().build().toString());
        //使用druid数据源需要指定druid的数据源type
        return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
    }

    /**
     * 动态数据源: 将多个数据源配置到自己实现的动态数据源类中,通过AOP在不同数据源之间动态切换
     * @return
     */
    @Primary
    @Bean(name = "dynamicDS")
    public DynamicDataSource dataSource() {
        logger.info("====加载数据源集合=====");
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        // 默认数据源
        dynamicDataSource.setDefaultTargetDataSource(dataSource1());
        // 配置多数据源
        Map<Object, Object> dsMap = new HashMap(5);
        dsMap.put("ds1", dataSource1());
        dsMap.put("ds2", dataSource2());
        dynamicDataSource.setTargetDataSources(dsMap);
        return dynamicDataSource;
    }

    /**
     * 配置@Transactional注解事物
     * @return
     */
    @Bean
    public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception {
        return new DataSourceTransactionManager(dataSource);
    }
}
